from flask import request, jsonify, Blueprint
import threading

from api.service.rule_config_service import rule_manager
from api.service.rule_storage_service import rule_storage
from api.service.rule_sync_service import reload_rule
from api.service.rule_transfer_service import transform_rule_to_workflow

storage_lock = threading.Lock()

app = Blueprint('rule_config', __name__)


# --- API 路由 ---
@app.route('/rules', methods=['POST'])
def create_rule():
    """
    创建一条新规则。
    POST /api/rules
    Body (JSON): 规则数据，必须包含 rule_code, attrClassify 等字段。
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "请求体必须是 JSON 格式"}), 400

        rule_code = data['rule_code']
        attr_classify = data['attrClassify']

        # 转换规则
        parse_data = transform_rule_to_workflow(data)
        # 添加新规则
        rule_storage.add_dict(attr_classify, rule_code, parse_data)
        rule_manager.add(rule_code, data)
    except Exception as e:
        return jsonify({"message": str(e)}), 404
    return jsonify({"message": "规则创建成功", "rule_code": rule_code}), 201


@app.route('/rules/<string:rule_code>', methods=['GET'])
def get_rule(rule_code: str):
    """
    根据类别和规则代码获取单条规则。
    GET /api/rules/<rule_code>
    """
    rule = rule_storage.get_dict_by_code(rule_code)

    if not rule:
        return jsonify({"error": f"未找到规则代码为 '{rule_code}' 的规则"}), 404

    return jsonify(rule), 200


@app.route('/reload_rules/<string:rule_code>', methods=['GET'])
def reload_rule_by_code(rule_code: str):
    try:
        reload_rule(rule_code=rule_code)
    except Exception as e:
        return jsonify({"message": str(e)}), 404
    return jsonify({"message": "success"}), 200


@app.route('/reload_rules', methods=['GET'])
def reload_rules():
    try:
        reload_rule()
    except Exception as e:
        return jsonify({"message": str(e)}), 404
    return jsonify({"message": "success"}), 200


@app.route('/rules/<string:attr_classify>', methods=['GET'])
def list_rules_by_classify(attr_classify: str):
    """
    获取指定类别下的所有规则。
    GET /api/rules/<attr_classify>
    """

    rules = rule_storage.get_dicts(attr_classify)

    # 如果类别不存在或为空，返回空列表
    if not rules:
        return jsonify([]), 200

    return jsonify(rules), 200


@app.route('/rules/<string:rule_code>', methods=['PUT'])
def update_rule(rule_code: str):
    """
    更新一条规则的全部内容。
    PUT /api/rules/<rule_code>
    Body (JSON): 规则的完整新数据。
    """
    data = request.get_json()
    if not data:
        return jsonify({"error": "请求体必须是 JSON 格式"}), 400

    # 新数据中的 rule_code 必须与 URL 中的 rule_code 一致
    if data['rule_code'] != rule_code:
        return jsonify({"error": "请求体中的 rule_code 必须与 URL 路径中的 rule_code 一致"}), 400
    try:
        rule_code = data['rule_code']
        attr_classify = data['attrClassify']
        # 转换规则
        parse_data = transform_rule_to_workflow(data)
        rule_storage.remove_by_code(rule_code)
        # 更新新规则
        rule_storage.add_dict(attr_classify, rule_code, parse_data)
        rule_manager.add(rule_code, data)
    except (KeyError, ValueError) as e:
        return jsonify({"error": str(e)}), 404
    return jsonify({"message": "规则更新成功", "rule_code": rule_code}), 200


@app.route('/rules/<string:rule_code>', methods=['DELETE'])
def delete_rule(rule_code: str):
    """
    删除一条规则。
    DELETE /api/rules/<rule_code>
    """
    try:
        rule_storage.remove_by_code(rule_code)
        rule_manager.delete(rule_code)
    except (KeyError, ValueError) as e:
        return jsonify({"error": str(e)}), 404

    return jsonify({"message": f"规则 '{rule_code}' 已删除"}), 200
